package com.hema.auction.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.hema.auction.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * author by john
 * 工具类
 */
public class Utils {
    /**
     * 字符串非空判断
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(CharSequence str) {
        return TextUtils.isEmpty(str) || str.equals("null");
    }

    /**
     * 验证手机号码是否合格
     *
     * @param str
     * @return
     */
    public static boolean isValidPhone(String str) {
        Pattern pattern = Pattern.compile("^[1][3-8]\\d{9}$");
        return pattern.matcher(str).matches();
    }

    /**
     * 验证邮箱地址是否合法
     *
     * @param strEmail
     * @return
     */
    public static boolean isValidEmail(String strEmail) {
        Pattern pattern = Pattern
                .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        return pattern.matcher(strEmail).matches();
    }


    /**
     * 获取App版本名称【字符串类型】
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    /**
     * 获取App版本号【整数类型】
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return 0;
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @param context
     * @param dpValue dp值
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        return (int) (dpValue * getDeviceDensity(context) + 0.5f);
    }

    /**
     * 获得设备的密度
     *
     * @param mContext
     * @return
     */
    public static float getDeviceDensity(Context mContext) {
        return mContext.getResources().getDisplayMetrics().density;
    }


    /**
     * 根据年 月 获取对应的月份天数
     *
     * @param year
     * @param month
     * @return
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    /**
     * 根据字符串格式日期获取年
     *
     * @param time
     * @return
     */
    public static String getYear(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "1950";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        return String.valueOf(calendar.get(calendar.YEAR));
    }

    /**
     * 根据字符串格式日期获取年
     *
     * @param time
     * @return
     */
    public static String getDateYear(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "1950";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        return String.valueOf(calendar.get(calendar.YEAR));
    }

    /**
     * 根据字符串格式日期获取天
     *
     * @param time
     * @return
     */
    public static String getDay(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "01";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        return String.valueOf(calendar.get(calendar.DAY_OF_MONTH));
    }


    /**
     * 根据字符串格式日期获取月
     *
     * @param time
     * @return
     */
    public static String getMonth(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "01";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        return String.valueOf(calendar.get(calendar.MONTH) + 1);
    }

    /**
     * 根据字符串格式日期获取月
     *
     * @param time
     * @return
     */
    public static String getDateMonth(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return "01";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        return String.valueOf(calendar.get(calendar.MONTH) + 1);
    }


    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getDateMonth() {
        Calendar a = Calendar.getInstance();
        return a.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前几号
     *
     * @return
     */
    public static int getDateDay() {
        Calendar a = Calendar.getInstance();
        return a.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public static String getTaday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(new Date());
    }


    /**
     * 获取当前日期
     *
     * @return
     */
    public static String getNowDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    /**
     * 格式化输出日期
     *
     * @param context 当前上下文
     * @param time    待格式化的时间字符串【格式：yyyy-MM-dd HH:mm:ss】
     * @return 返回格式化过的时间字符串
     * <p/>
     * <pre>
     *         	   小于等于0秒显示刚刚
     *             6秒-59秒显示x秒前
     *             1分钟-59分钟显示x分钟前，秒数舍去
     *             1小时-23小时59分显示x小时前，分钟数舍去
     *             1天前显示昨天，小时舍去
     *             2天前显示前天，小时舍去
     *             超过5天前显示完整日期和时间，例如：2014-05-10 12:23。但如果时当年的，不显示年份，例如：05-10 12:23。
     * </pre>
     * @throws ParseException
     */
    public static String formatDisplayTime(Context context, String time) {
        if (Utils.isEmpty(time)) {
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(time);
        } catch (Exception e) {
            e.printStackTrace();
            return time;
        }

        long snstime = d.getTime() / 1000;
        Date curDate = new Date();
        long currentTime = curDate.getTime() / 1000;

        if ((currentTime - snstime) <= 0) {
            return "刚刚";
        } else if ((currentTime - snstime) < 60) {
            return (currentTime - snstime) + "秒前";
        } else if ((currentTime - snstime) < 60 * 60) {
            return (currentTime - snstime) / 60 + "分钟前";
        } else if ((currentTime - snstime) < 60 * 60 * 24) {
            return (currentTime - snstime) / (60 * 60) + "小时前";
        } else if ((currentTime - snstime) > 60 * 60 * 24
                && (currentTime - snstime) < 60 * 60 * 24 * 2) {
            return "昨天";
        } else if ((currentTime - snstime) > 60 * 60 * 24 * 2
                && (currentTime - snstime) < 60 * 60 * 24 * 3) {
            return "前天";
        } else {
            // 判断年
            if (d.getYear() < curDate.getYear()) {
                String result = sdf.format(d);
                return result.substring(0, result.length() - 3);
            } else {
                sdf = new SimpleDateFormat("yyyy-MM-dd");
                return sdf.format(d);
            }

        }
    }

    public static String timedate(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }

    /**
     * 检测外部外部存储是否存在
     *
     * @return
     */
    public static boolean isSdcardExist() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    /**
     * 获得设备的宽度
     *
     * @param mContext
     * @return
     */
    public static int getDeviceWidth(Context mContext) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay()
                .getMetrics(metrics);
        return metrics.widthPixels;
    }

    /**
     * 判断密码是否合法 6-20位数字、字母
     *
     * @param str
     * @return
     */
    public static boolean isValidPwd(String str) {
        Pattern pattern = Pattern.compile("[0-9a-zA-Z]{6,20}");
        return pattern.matcher(str).matches();
    }

    /**
     * 把文件转成base64编码的数据
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(File file) throws Exception {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /**
     * 判断姓名是否合法
     *
     * @param str
     * @return
     */
    public static boolean isRealName(String str) {
        Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]{2,10}");
        return pattern.matcher(str).matches();
    }


    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(Context context) {
        AppCompatActivity activity = (AppCompatActivity) context;
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示键盘
     */
    public static void showKeyboard(Context context, EditText editText) {
        AppCompatActivity activity = (AppCompatActivity) context;
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        IBinder token = activity.getCurrentFocus().getWindowToken();
        if (token != null) {
            imm.showSoftInputFromInputMethod(token, 0);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param path    文件路劲
     */
    public static void installAPK(Context context, String path) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(path)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * toast提示
     *
     * @param context
     * @param msg
     */
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }

    /**
     * toast提示
     *
     * @param context
     * @param resId
     */
    public static void showToast(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_LONG).show();
    }

    /**
     * 字符串转md5
     *
     * @param string
     * @return
     */
    public static String stringToMD5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString().toLowerCase();
    }

    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = -1;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    public static String countDown(int time) {
        if (time >= 10)
            return "00:00:" + time;
        else {
            if (time <= 0)
                return "00:00:00";
            return "00:00:0" + time;
        }
    }

    public static String priceUnitFormat(Context context, String price) {
        if (isEmpty(price))
            return context.getString(R.string.price_unit_format, 0f);
        return context.getString(R.string.price_unit_format, Float.valueOf(price));
    }

    public static String priceUnitFormat(Context context, float price) {
        return context.getString(R.string.price_unit_format, price);
    }

    public static String priceFormat(Context context, String price) {
        if (isEmpty(price))
            return context.getString(R.string.price_format, 0f);
        return context.getString(R.string.price_format, Float.valueOf(price));
    }

    public static String priceFormat(Context context, float price) {
        return context.getString(R.string.price_format, price);
    }

    public static String savaFormat(Context context, String dPrice, String mPrice) {
        if (isEmpty(dPrice))
            dPrice = "0";
        if (isEmpty(mPrice))
            mPrice = "1";
        float dealPrice = Float.valueOf(dPrice);
        float marktPrice = Float.valueOf(mPrice);
        if (marktPrice == 0)
            return context.getString(R.string.save_format, 0);
        float save = 100 - dealPrice / marktPrice * 100;
        return context.getString(R.string.save_format, save);
    }

    /**
     * 往url拼接参数
     *
     * @param url
     * @param params
     * @return
     */
    public static String formatUrl(String url, HashMap<String, String> params) {
        if (params != null) {
            Uri uri = Uri.parse(url);
            Uri.Builder builder = uri.buildUpon();
            for (String key : params.keySet()) {
                builder.appendQueryParameter(key, params.get(key));
            }
            url = builder.build().toString();
        }
        return url;
    }

    /**
     * 根据url解析参数值
     *
     * @param url
     * @param key
     * @return
     */
    public static String getParameter(String url, String key) {
        Uri uri = Uri.parse(url);
        return uri.getQueryParameter(key);
    }


    /**
     * 获取渠道号
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        String channel = "official";
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getString("JPUSH_CHANNEL");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channel;
    }
}
